package com.loongtech.bi.action.newsystem;

import com.loongtech.bi.action.authManagement.ResultData;
import com.loongtech.bi.entity.system.EntitySysUser;
import com.loongtech.bi.manager.system.SysLogManager;
import com.loongtech.bi.manager.system.SysUserManager;
import com.loongtech.bi.support.Session;
import com.loongtech.core.util.RetCode;
import com.loongtech.core.util.Utils;
import jodd.util.StringUtil;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * Author: yuri
 * Description: 密码修改
 * Date: 11:08 2017/5/23
 */
@RestController
@Scope("prototype")
@RequestMapping("/password")
public class PasswordChangeAction implements java.io.Serializable {
    private static final long serialVersionUID = 5L;
    @Resource
    private Session session;
    @Resource
    private SysUserManager sysUserManager;
    @Resource
    private SysLogManager sysLogManager;

    @RequestMapping(value = "modify.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ResultData<String> change(@RequestParam String userName, @RequestParam String oldPassword, @RequestParam String newPassword) {
        if (StringUtil.isEmpty(userName)) {
            return new ResultData<>(RetCode.eEmptyUserNameError.getErrorcode(), RetCode.eEmptyUserNameError.getErrorMsg());
        }
        if (StringUtil.isEmpty(oldPassword) || StringUtil.isEmpty(newPassword)) {
            return new ResultData<>(RetCode.eEmptyPassWord.getErrorcode(), RetCode.eEmptyPassWord.getErrorMsg());
        }
        try {
            EntitySysUser curUser = sysUserManager.getBy(EntitySysUser.K.username, userName);
            if (null == curUser || null == curUser.getPassword() || !curUser.getPassword().equals(Utils.md5(oldPassword))) {
                return new ResultData<>(RetCode.eErrPassWordUserName.getErrorcode(), RetCode.eErrPassWordUserName.getErrorMsg());
            }
            curUser.setPassword(Utils.md5(newPassword));
            sysUserManager.merge(curUser);
            sysLogManager.addLog(userName, "修改密码成功" + userName);
            return ResultData.success();
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResultData.otherException();
        }
    }
}
